package com.mindskip.xzs.controller.admin;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.mindskip.xzs.base.BaseApiController;
import com.mindskip.xzs.base.RestResponse;
import com.mindskip.xzs.domain.ExamPaperAnswer;
import com.mindskip.xzs.domain.Level;
import com.mindskip.xzs.domain.Subject;
import com.mindskip.xzs.domain.User;
import com.mindskip.xzs.domain.Video;
import com.mindskip.xzs.domain.enums.ExamPaperTypeEnum;
import com.mindskip.xzs.service.*;
import com.mindskip.xzs.utility.DateTimeUtil;
import com.mindskip.xzs.utility.ExamUtil;
import com.mindskip.xzs.utility.PageInfoHelper;
import com.mindskip.xzs.viewmodel.admin.user.UserPageRequestVM;
import com.mindskip.xzs.viewmodel.admin.user.UserResponseVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperSubmitItemVM;
import com.mindskip.xzs.viewmodel.student.exam.ExamPaperSubmitVM;
import com.mindskip.xzs.viewmodel.student.exampaper.ExamPaperAnswerPageResponseVM;
import com.mindskip.xzs.viewmodel.admin.paper.ExamPaperAnswerPageRequestVM;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController("AdminExamPaperAnswerController")
@RequestMapping(value = "/api/admin/examPaperAnswer")
public class ExamPaperAnswerController extends BaseApiController {

    private final ExamPaperAnswerService examPaperAnswerService;
    private final SubjectService subjectService;
    private final UserService userService;
    private final ExamPaperService examPaperService;
    private final VideoService videoService;
    private final LevelService levelService;

    @Autowired
    public ExamPaperAnswerController(ExamPaperAnswerService examPaperAnswerService, SubjectService subjectService, UserService userService, ExamPaperService examPaperService, VideoService videoService, LevelService levelService) {
        this.examPaperAnswerService = examPaperAnswerService;
        this.subjectService = subjectService;
        this.userService = userService;
        this.examPaperService = examPaperService;
        this.videoService = videoService;
        this.levelService = levelService;
    }


    @RequestMapping(value = "/page", method = RequestMethod.POST)
    public RestResponse<PageInfo<ExamPaperAnswerPageResponseVM>> pageJudgeList(@RequestBody ExamPaperAnswerPageRequestVM model) {
        if (StringUtils.isEmpty(model.getPaperName())) {
            model.setPaperName(null);
        }
        if (StringUtils.isEmpty(model.getRealName())) {
            model.setRealName(null);
        }

        if (StringUtils.isEmpty(model.getUserLevel())) {
            model.setUserLevel(null);
        }

        PageInfo<ExamPaperAnswer> pageInfo = examPaperAnswerService.adminPage(model);
        PageInfo<ExamPaperAnswerPageResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> {
            ExamPaperAnswerPageResponseVM vm = modelMapper.map(e, ExamPaperAnswerPageResponseVM.class);
            Subject subject = subjectService.selectById(vm.getSubjectId());
            vm.setDoTime(ExamUtil.secondToVM(e.getDoTime()));
            vm.setPaperTypeStr(ExamPaperTypeEnum.fromCode(vm.getPaperType()).getName());
            if (e.getPaperName().equals("实操考试")) {
                vm.setPaperScore("实操成绩");
                Map<String,String> stringMap = getPassResult(e);
                String result = stringMap.get("result");
                vm.setUserScore(result);
                vm.setPaperTypeStr("正式考试");
                vm.setQuestionCorrect(Integer.parseInt(stringMap.get("passSize")));
            } else {
                vm.setUserScore(ExamUtil.scoreToVM(e.getUserScore()));
                vm.setPaperScore(ExamUtil.scoreToVM(e.getPaperScore()));
            }
            vm.setSystemScore(ExamUtil.scoreToVM(e.getSystemScore()));
            vm.setSubjectName(subject.getName());
            vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            User user = userService.selectById(e.getCreateUser());
            vm.setUserName(user.getUserName());
            vm.setRealName(user.getRealName());
            vm.setIdCardNo(user.getIdCardNo());
            vm.setAge(user.getAge());
            vm.setPhone(user.getPhone());
            vm.setUserLevel(user.getUserLevel());
            vm.setSexStr(user.getSexStr(user.getSex()));
            vm.setNationality(user.getNationality());
            vm.setEducation(user.getEducationStr(user.getEducation()));
            vm.setArmy(user.getArmyStr(user.getArmy()));
            vm.setLevelName(user.getLevelName());
            vm.setPolitics(user.getPoliticsStr(user.getPolitics()));
            vm.setLocation(user.getLocation());
            vm.setHealth(user.getHealth());
            vm.setHeight(user.getHeight());
            return vm;
        });
        return RestResponse.ok(page);
    }


    /**
     * 用户excel导出
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/excel", method = RequestMethod.POST)
    public void pageListExcel(@RequestBody ExamPaperAnswerPageRequestVM model, HttpServletResponse response) {
        if (StringUtils.isEmpty(model.getPaperName())) {
            model.setPaperName(null);
        }
        if (StringUtils.isEmpty(model.getRealName())) {
            model.setRealName(null);
        }
        model.setPageIndex(0);
        model.setPageSize(150);
        PageInfo<ExamPaperAnswer> pageInfo = examPaperAnswerService.adminPageExcel(model);
        PageInfo<ExamPaperAnswerPageResponseVM> page = PageInfoHelper.copyMap(pageInfo, e -> {
            ExamPaperAnswerPageResponseVM vm = modelMapper.map(e, ExamPaperAnswerPageResponseVM.class);
            Subject subject = subjectService.selectById(vm.getSubjectId());
            vm.setDoTime(ExamUtil.secondToVM(e.getDoTime()));
            if (e.getPaperName().equals("实操考试")) {
                vm.setPaperScore("实操成绩");
                Map<String,String> stringMap = getPassResult(e);
                String result = stringMap.get("result");
                vm.setUserScore(result);
            } else {
                vm.setUserScore(ExamUtil.scoreToVM(e.getUserScore()));
                vm.setPaperScore(ExamUtil.scoreToVM(e.getPaperScore()));
            }
            vm.setSystemScore(ExamUtil.scoreToVM(e.getSystemScore()));
            vm.setSubjectName(subject.getName());
            vm.setCreateTime(DateTimeUtil.dateFormat(e.getCreateTime()));
            User user = userService.selectById(e.getCreateUser());
            vm.setUserName(user.getUserName());
            vm.setRealName(user.getRealName());
            vm.setIdCardNo(user.getIdCardNo());
            vm.setPhone(user.getPhone());
            vm.setSexStr(user.getSexStr(user.getSex()));
            vm.setPaperTypeStr(ExamPaperTypeEnum.fromCode(vm.getPaperType()).getName());
            vm.setNationality(user.getNationality());
            vm.setEducation(user.getEducationStr(user.getEducation()));
            vm.setArmy(user.getArmyStr(user.getArmy()));
            vm.setLevelName(user.getLevelName());
            vm.setPolitics(user.getPoliticsStr(user.getPolitics()));
            vm.setLocation(user.getLocation());
            vm.setHealth(user.getHealth());
            vm.setHeight(user.getHeight());
            return vm;
        });

        List<ExamPaperAnswerPageResponseVM> examPaperAnswerPageResponseVMS = page.getList();
        if (CollUtil.isNotEmpty(examPaperAnswerPageResponseVMS)) {
            ExcelWriter writer = ExcelUtil.getWriter();
            //自定义标题别名
            writer.setOnlyAlias(true);
            writer.addHeaderAlias("paperName", "试卷名称");
            writer.addHeaderAlias("subjectName", "考试类型");
            writer.addHeaderAlias("userName", "昵称");
            writer.addHeaderAlias("realName", "真实姓名");
            writer.addHeaderAlias("sexStr", "性别");
            writer.addHeaderAlias("phone", "电话");
            writer.addHeaderAlias("idCardNo", "身份证号码");
            writer.addHeaderAlias("nationality","民族");
            writer.addHeaderAlias("education","文化程度");
            writer.addHeaderAlias("army","兵役状况");
            writer.addHeaderAlias("levelName","班级");
            writer.addHeaderAlias("politics","政治面貌");
            writer.addHeaderAlias("location","住址");
            writer.addHeaderAlias("health","健康状况");
            writer.addHeaderAlias("height","身高");
            writer.addHeaderAlias("paperScore", "考试总分");
            writer.addHeaderAlias("userScore", "学员成绩");
            writer.addHeaderAlias("doTime", "耗时");
            writer.addHeaderAlias("createTime", "提交时间");

//            // 合并单元格后的标题行，使用默认标题样式
//            writer.merge(2, "学员信息");
            // 一次性写出内容，使用默认样式，强制输出标题
            writer.write(examPaperAnswerPageResponseVMS, true);
            //out为OutputStream，需要写出到的目标流
            //response为HttpServletResponse对象
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
            String name = "chengji";
            response.setHeader("Content-Disposition", "attachment;filename=" + name + ".xls");
            ServletOutputStream out = null;
            try {
                out = response.getOutputStream();
                writer.flush(out, true);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                // 关闭writer，释放内存
                writer.close();
            }
            //此处记得关闭输出Servlet流
            IoUtil.close(out);
        }
    }


    private List<User> getUserList(List<User> userList) {
        List<Level> keyValues = levelService.getLevelList();
        Map<Integer, String> map =
                keyValues.stream().collect(Collectors.toMap(
                        Level::getLevel,
                        Level::getLevelName,
                        (key1, key2) -> key2
                ));

        for (User user : userList) {
            user.getUserInfoDetail(user);
            String levelName = map.get(user.getUserLevel());
            user.setLevelName(levelName);
        }
        return userList;
    }

    private Map<String,String> getPassResult(ExamPaperAnswer examPaperAnswer) {
        Map<String,String> mapResult = new HashMap<>();
        String result = "";
        String passSize = "0";
        mapResult.put("result",result);
        mapResult.put("passSize",passSize);
        List<String> resultPass = new ArrayList<>();
        ExamPaperSubmitVM answer = examPaperAnswerService.examPaperAnswerToVM(examPaperAnswer.getId());
        if (examPaperAnswer.getPaperName().contains("实操考试")) {
            List<ExamPaperSubmitItemVM> answerItems = answer.getAnswerItems();
            if (CollUtil.isNotEmpty(answerItems)) {
                for (ExamPaperSubmitItemVM examPaperSubmitItemVM : answerItems) {
                    //查询questionId 通过状态
                    Integer questionId = examPaperSubmitItemVM.getQuestionId();
                    if (null == questionId) {
                        questionId = 0;
                    }
                    Video video = new Video();
                    video.setCreateUserId(examPaperAnswer.getCreateUser());
                    video.setTag(String.valueOf(questionId));
                    Video video1 = videoService.getVideoByTag(video);
                    if (null != video1) {
                        //获取是否通过
                        int isCheck = video1.getIsCheck();
                        if (isCheck == 0) {
                            result = "批阅中";
                            mapResult.put("result",result);
                            mapResult.put("passSize",passSize);
                            return mapResult;
                        } else {
                            int isPass = video1.getIsPass();
                            if (isPass == 0) {
                                result = "未通过";
                                mapResult.put("result",result);
                                mapResult.put("passSize",passSize);
                                return mapResult;
                            } else {
                                result = "通过";
                                resultPass.add(result);
                            }
                        }
                    }

                }
            }
        }
        if (CollUtil.isNotEmpty(resultPass) && resultPass.size() > 2) {
            result = "通过";
        }
        if (StringUtils.isEmpty(result)) {
            result = "批阅中";
        }
        int size = resultPass.size();
        mapResult.put("result",result);
        mapResult.put("passSize",String.valueOf(size));
        return mapResult;
    }


}
